//获取应用实例
const app = getApp();

//声明全局变量
let proListToTop = [], menuToTop = [], MENU = 0, windowHeight, timeoutId;
// MENU ==> 是否为点击左侧进行滚动的，如果是，则不需要再次设置左侧的激活状态
Page({

  data: {
    staticImg: app.globalData.staticImg,
    currentActiveIndex: 0,
    // 接口返回的商品数组
    navList: [],
    animate:'',
    goodsList:[],
  },
  onLoad: function (e) {
    this.getAllList();
    // 确保页面数据已经刷新完毕~
    setTimeout(() => {
      this.getAllRects()
    }, 20)

    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log(res)
        if (res.data != '') {
          app.globalData.token = res.data
        }
        // console.log("token=" + app.globalData.token)
      },
    })
  },


  //获取顶级淘宝商品分类列表
  getAllList(){
    var that=this;
    wx.request({
      url: app.globalData.api + '/app.php?c=TaobaoCat&a=getTopCatList',
      data:
      {
       
      },
      header: {
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        for (var i = 0; i < res.data.data.list.length; i++) {
          // res.data.data.list[i].img = app.globalData.imgUrl + "" + res.data.data.list[i].img;
         
        }
        that.setData({
          navList: res.data.data.list
        })
        // console.log(that.data.navList);
        that.getList(0);
      }, fail: function () {

      }
    });
  },


  //获取子级淘宝商品分类列表
  getList(position) {
    console.log(position)
    wx.showLoading({
      title: '加载中',
      mask: false
    })
    var that = this;
    wx.request({
      url: app.globalData.api + '/app.php?c=TaobaoCat&a=getSubListByParent',
      data:
      {
        pid: that.data.navList[position].taobao_cat_id,
      },
      header: {
        "Content-Type": "application/x-www-form-urlencoded",
        'platform': '' + app.globalData.platform,
        'version': '' + app.globalData.version,
      },
      method: 'POST',
      dataType: 'json',
      success: function (res) {
        console.log(res);
        wx.hideLoading();
        if (res.data.data.list.length > 0) {
          for (var i = 0; i < res.data.data.list.length; i++) {
            res.data.data.list[i].icon = app.globalData.imgUrl + "" + res.data.data.list[i].icon;
            that.setData({
              goodsList: res.data.data.list
            })
          }
        } else {
          that.setData({
            goodsList: ""
          })
        }
      }, fail: function () {
        wx.hideLoading();
      }
    });
  },
  searchSubmit: function (e) {
    console.info('携带数据为：', e.detail.value)
    var that = this
    var inputVal = that.data.recordValue
    var searchRecord = this.data.searchRecord
    if (inputVal == '' || inputVal == undefined) {
      //输入为空时的处理
      console.log("inputVal is null")
    }
    else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      that.setData({
        searchRecord: searchRecord
      })
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
    wx.navigateTo({
      url: '/pages/shop/search-list?name=' + e.detail.value,
    })
  },

  openHistorySearch: function () {
    this.setData({
      searchRecord: wx.getStorageSync('searchRecord') || [],//若无储存则为空
    })
  },
  recordInput: function (e) {
    this.setData({
      recordValue: e.detail.value
    })
  },
  search: function () {
    var that = this
    var inputVal = that.data.recordValue
    var searchRecord = this.data.searchRecord
    if (inputVal == '') {
      //输入为空时的处理
    }
    else {
      //将搜索值放入历史记录中,只能放前五条
      if (searchRecord.length < 5) {
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      else {
        searchRecord.pop()//删掉旧的时间最早的第一条
        searchRecord.unshift(
          {
            value: inputVal,
            id: searchRecord.length
          }
        )
      }
      that.setData({
        searchRecord: searchRecord
      })
      //将历史记录数组整体储存到缓存中
      wx.setStorageSync('searchRecord', searchRecord)
    }
  },
  goodDetail:function(e){
    console.log(e)
    console.log(app.globalData.token)
    if(app.globalData.token!=''){
      console.log(e);
      wx.navigateTo({
        url: 'main-good-list?id='+e.currentTarget.dataset.name,
      })
    }else{
      wx.reLaunch({
        url: '/pages/mine/login',
      })
    }
      
  },

  changeMenu(e) {
    // console.log(proListToTop);
    // 改变左侧tab栏操作
    if (Number(e.target.id) === this.data.currentActiveIndex) return
    MENU = 1
    this.setData({
      currentActiveIndex: Number(e.target.id),
      rightProTop: proListToTop[Number(e.target.id)]
    })
    // console.log("position="+this.data.currentActiveIndex);
    this.setMenuAnimation(Number(e.target.id))
    this.getList(this.data.currentActiveIndex);
    //
  },

 
  scroll(e) {
    // console.log(e);
    for (let i = 0; i < proListToTop.length; i++) {
      if (e.detail.scrollTop < proListToTop[i] && i !== 0 && e.detail.scrollTop > proListToTop[i - 1]) {
        return this.setDis(i)
      }
    }
    // 找不到匹配项，默认显示第一个数据
    if (!MENU) {
      this.setData({
        currentActiveIndex: 0
      })
    }
    MENU = 0
  },
  setDis(i) {
    // 设置左侧menu栏的选中状态
    if (i !== this.data.currentActiveIndex + 1 && !MENU) {
      this.setData({
        currentActiveIndex: i - 1
      })
    }
    MENU = 0
    this.setMenuAnimation(i)
  },
  setMenuAnimation(i) {
    // 设置动画，使menu滚动到指定位置。
    let self = this
  },
  getActiveReacts() {
    wx.createSelectorQuery().selectAll('.menu-active').boundingClientRect(function (rects) {
      return rects[0].top
    }).exec()
  },
  getAllRects() {
    wx.createSelectorQuery().selectAll('.pro-item').boundingClientRect(function (rects) {
      rects.forEach(function (rect) {
        console.log(rect)
        // 这里减去44是根据你的滚动区域距离头部的高度，如果没有高度，可以将其删去
        proListToTop.push(rect.top - 44)
      })
    }).exec()
    // 获取menu数组的位置信息
    wx.createSelectorQuery().selectAll('.menu-item').boundingClientRect(function (rects) {
      wx.getSystemInfo({
        success: function (res) {
          // console.log(res);
          windowHeight = res.windowHeight / 2
          // console.log(windowHeight)
          rects.forEach(function (rect) {
            menuToTop.push({
              top: rect.top,
              // animate: rect.top > windowHeight
            })
          })
        }
      })
    }).exec()
  },
  // 获取系统的高度信息
  getSystemInfo() {
    let self = this
    wx.getSystemInfo({
      success: function (res) {
        windowHeight = res.windowHeight / 2
      }
    })
  },

})